package checkrank;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

import server.GetBing;
import server.GetContent;

@SuppressWarnings("serial")
public class CheckServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setCharacterEncoding("utf-8");
		
		String google = req.getParameter("google").trim();
		String title = req.getParameter("title").trim().replaceAll("[\\|]+$", "");
		String domain = req.getParameter("domain").trim();
		
		String[] arrGoogle = google.split(" ");
		String[] arrTitle = title.split("\\|");
		
		HashMap<String,String> listGoogle = new HashMap<String,String>();
		
		for (int i = 0; i < arrTitle.length; i++) {
			listGoogle.put(arrTitle[i], arrGoogle[i]);
		}

		String str = req.getParameter("name");

		str = URLDecoder.decode(str,"UTF-8");

		String[] arr = new String[listGoogle.size()];
		
		int j=0;
		for (String key : listGoogle.keySet()) {
			if(listGoogle.get(key).equals("www.bing.com"))
			{
				new GetBing(str,listGoogle.get(key),arr,j);
			} else {
				new GetContent(str,listGoogle.get(key),arr,j);
			}
			j++;
        }

		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
		System.out.println(arr);
		req.setAttribute("arr", arr);
		req.setAttribute("listGoogle", listGoogle);
		req.setAttribute("domain", domain);
		
		DBCollection colls = Data.data("keywordunique");
		DBObject db = colls.findOne(new BasicDBObject("name",str));
		if(db == null)
		{
			BasicDBObject key = new BasicDBObject();
			key.put("name", str);
	
			key.put("date", new Date().getTime());
			colls.insert(key);
		}
		
		try {
			req.getRequestDispatcher("/check.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}